<template>
  <div class="chat-container">
    <div class="chat-history">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
        <div class="message-content">{{ message.content }}</div>
      </div>
      <div v-if="loading" class="message assistant">
        <div class="message-content">思考中...</div>
      </div>
    </div>
    <div class="chat-input">
      <textarea v-model="userInput" @keyup.enter="sendMessage" placeholder="输入消息..."></textarea>
      <button @click="sendMessage">发送</button>
      <button @click="clearConversation">清空对话</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const messages = ref([]);
const userInput = ref('');
const loading = ref(false);

const sendMessage = async () => {
  if (!userInput.value.trim()) return;
  
  // 添加用户消息
  messages.value.push({ role: 'user', content: userInput.value });
  const currentInput = userInput.value;
  userInput.value = '';
  loading.value = true;
  
  try {
    // 调用后端API
    const response = await axios.post('http://localhost:8080/api/chat', {
      message: currentInput
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    // 添加AI回复
    messages.value.push({ role: 'assistant', content: response.data });
  } catch (error) {
    console.error('调用API失败:', error);
    messages.value.push({ role: 'assistant', content: '抱歉，出错了: ' + error.message });
  } finally {
    loading.value = false;
  }
};

const clearConversation = async () => {
  try {
    await axios.post('http://localhost:8080/api/chat/clear');
    messages.value = [];
  } catch (error) {
    console.error('清除对话失败:', error);
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.message {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 5px;
}

.message.user {
  background-color: #e3f2fd;
  margin-left: 20%;
  text-align: right;
}

.message.assistant {
  background-color: #f5f5f5;
  margin-right: 20%;
}

.message-content {
  white-space: pre-wrap;
}

.chat-input {
  display: flex;
  gap: 10px;
}

.chat-input textarea {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  resize: none;
  height: 60px;
}

.chat-input button {
  padding: 10px 15px;
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.chat-input button:hover {
  background-color: #1565c0;
}
</style>